<?php
/**
 * Class Cart
 * Desc  购物车
 * Create on 2022/10/11 11:33
 * Create by wangyafang
 */

namespace app\api\controller\wdsxh\mall;

use app\admin\model\wdsxh\mall\Goods;
use app\common\controller\Api;
use think\Db;
use think\exception\PDOException;
use think\Exception;
use think\exception\ValidateException;

class Cart extends Api
{
    protected $noNeedLogin = ['edit'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $model = '';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\wdsxh\mall\Cart();
    }

    //加入购物车
    //param:token goods_id
    public function add()
    {
        $user_id = $this->auth->id;
        $goods_id = $this->request->post('goods_id');
        $param = $this->request->param();

        //判断用户是否已加入购物车
        $cartWhere['user_id'] = array('eq',$user_id);
        $cartWhere['goods_id'] = array('eq',$goods_id);
        $cartId = $this->model->where($cartWhere)->value('id');
        if ($cartId) {
            $this->error('已加入购物车');
        }

        //判断商品是否已下架
        $goodsObj = (new Goods())->where('id',$goods_id)->field('status,member_unit_id,store_id')->find();
        if ($goodsObj['status'] != 'normal') {
            $this->error('商品已下架');
        }

        //添加数据
        $create_data = [];
        if($goodsObj['member_unit_id']) {
            $create_data['type'] = 2;//商户
            $create_data['store_id'] = $goodsObj['store_id'];
        } else {
            $create_data['type'] = 1;//平台
            $create_data['store_id'] = -1;
        }
        $create_data['user_id'] = $user_id;
        $create_data['goods_id'] = $goods_id;
        $create_data['goods_num'] = isset($param['goods_num']) ? $param['goods_num'] : 1;
        $create_data['buy_now'] = 2;
        Db::startTrans();
        try {
            $this->model->allowField(true)->save($create_data);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('加入成功',['id'=>$this->model->id]);

    }

    //修改购物车数量
    public function edit(){
        $param = $this->request->param();
        $user_id = $this->auth->id;
        $catr_edit = (new \app\api\model\wdsxh\mall\Cart())
            ->where('id',$param['cart_id'])
            ->where('user_id',$user_id)
            ->where('buy_now',2)
            ->update(['goods_num' => $param['goods_num']]);
        if($catr_edit){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }

    //购物车列表
    //param:token
    public function list()
    {
        $user_id = $this->auth->id;
        $cartWhere['cart.user_id'] = array('eq',$user_id);
        $cartWhere['cart.buy_now'] = array('eq','2');
        $cartWhere['cart.paid'] = array('eq','0');
        $data = $this->model
            ->alias('cart')
            ->where($cartWhere)
            ->order('cart.createtime desc,cart.id desc')
            ->join('wdsxh_mall_goods goods','goods.id = cart.goods_id')
            ->field('cart.id cart_id,cart.goods_id,cart.goods_num,cart.store_id,
            goods.name goods_name,goods.image goods_image,goods.price goods_price')
            ->select();
        foreach ($data as $k=>&$v) {
            $v['goods_image'] = wdsxh_full_url($v['goods_image']);
        }
        $this->success('请求成功',$data);

    }

    //拆分购物车列表数据
    public function splitCartData($data)
    {
        $array = array();
        foreach ($data as $k=>&$v) {
            $v['store_image'] = wdsxh_full_url($v['store_image']);
            $v['goods_image'] = wdsxh_full_url($v['goods_image']);
            if(!in_array($v['store_id'],array_column($array,'store_id'))) {//没有父级店铺
                if($v['store_id'] == -1) {
                    $v['store_name'] = '商会自营';
                }
                $child = [
                    'goods_id'=>$v['goods_id'],
                    'goods_num'=>$v['goods_num'],
                    'goods_name'=>$v['goods_name'],
                    'goods_image'=>$v['goods_image'],
                    'goods_price'=>$v['goods_price'],
                ];
                $array[$k]['cart_id'] = $v['cart_id'];
                $array[$k]['store_id'] = $v['store_id'];
                $array[$k]['store_name'] = $v['store_name'];
                $array[$k]['store_image'] = $v['store_image'];
                $array[$k]['child'][] = $child;
            }
            else {
                $array_key = array_search($v['store_id'],array_column($array,'store_id'));
                if($array_key !== false) {
                    $array[$array_key]['child'][] = [
                        'goods_id'=>$v['goods_id'],
                        'goods_num'=>$v['goods_num'],
                        'goods_name'=>$v['goods_name'],
                        'goods_image'=>$v['goods_image'],
                        'goods_price'=>$v['goods_price'],
                    ];
                }
            }
        }
        return $array;
    }

    //清除购物车
    //param:token  ids列表id
    public function del()
    {
        $cart_ids = $this->request->post('cart_ids');
        $cart_ids_array = explode(',',$cart_ids);
        $list = $this->model->where('id', 'in', $cart_ids_array)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            Db::commit();
        }  catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }

    }

    //判断是否加入购物车
    public function cart_status(){
        $id = $this->request->param('id');
        $user_id = $this->auth->id;
        $data = (new \app\api\model\wdsxh\mall\Cart())
            ->where('goods_id',$id)
            ->where('user_id',$user_id)
            ->where('deletetime','NULL')
            ->find();
        if ($data){
            $cart_data['cart_status'] = 1;
        }else{
            $cart_data['cart_status'] = 0;
        }
        $this->success('请求成功',$cart_data);
    }

    //清除购物车
    //param:token  ids列表id
    public function cart_del()
    {
        $cart_ids = $this->request->post('goods_id');
        $user_id = $this->auth->id;
        $cart_ids_array = explode(',',$cart_ids);
        $list = $this->model->where('goods_id', 'in', $cart_ids_array)
            ->where('user_id',$user_id)
            ->where('deletetime','NULL')->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }

    }
}



 